package com.zhu.esyblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhu.esyblog.Utils.BeanCopyUtils;
import com.zhu.esyblog.Utils.UserThreadLocal;
import com.zhu.esyblog.dos.Archives;
import com.zhu.esyblog.mapper.ArticleBodyMapper;
import com.zhu.esyblog.mapper.ArticleTagMapper;
import com.zhu.esyblog.pojo.*;
import com.zhu.esyblog.mapper.ArticleMapper;
import com.zhu.esyblog.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhu.esyblog.service.ISysUserService;
import com.zhu.esyblog.service.ITagService;
import com.zhu.esyblog.vo.ArticleParam;
import com.zhu.esyblog.vo.ArticleVo;

import com.zhu.esyblog.vo.TagVo;
import org.joda.time.DateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stx
 * @since 2022-06-22
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {
    private final Logger logger= LoggerFactory.getLogger(ArticleServiceImpl.class);
    @Autowired
    private  ArticleMapper articleMapper;
    @Autowired
    private ITagService tagService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    /**
     * 首页文章列表查询
     * @param pageBean
     * @return
     */
    @Override
    public RespBean listArticle(PageBean pageBean) {
        Page<Article> page=new Page<>(pageBean.getPage(),pageBean.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        if(pageBean.getCategoryId()!=null){
            queryWrapper.eq(Article::getCategoryId,pageBean.getCategoryId());
        }
        List<Long> articleIdList=new ArrayList<>();
        if(pageBean.getTagId()!=null){
            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageBean.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
            for (ArticleTag articleTag : articleTags) {
                articleIdList.add(articleTag.getArticleId());
            }
            if(articleIdList.size()>0){
                queryWrapper.in(Article::getId,articleIdList);
            }
        }
        //按照是否置顶排序
        //按照时间倒叙
        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
        Page<Article> articlePage = articleMapper.selectPage(page,queryWrapper);
        List<Article> records = articlePage.getRecords();
        List<ArticleVo> articleVoList=copyList(records,true,true);
        return RespBean.success("success",articleVoList);
    }

    /**
     * 首页最热文章
     * @param limit
     * @return
     */
    @Override
    public RespBean hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        List<Article> articleList = articleMapper.selectList(queryWrapper);
        return RespBean.success("success",copyList(articleList,false,false));
    }

    /**
     * 最新文章
     * @param limit
     * @return
     */
    @Override
    public RespBean newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        List<Article> articleList = articleMapper.selectList(queryWrapper);
        List<ArticleVo> articleVoList = BeanCopyUtils.copyBeanList(articleList, ArticleVo.class);
        return RespBean.success("success",articleVoList);
    }

    @Override
    public RespBean listArchives() {
       List<Archives> archives=articleMapper.listArchives();
        return RespBean.success("success",archives);
    }

    /**
     * 发布文章
     * @param articleParam
     * @return
     */
    @Override
    public RespBean publish(ArticleParam articleParam) {
        //加入登录拦截
        SysUser user = UserThreadLocal.get();
        if(null==user){
            return RespBean.error("请先登录！",500);
        }
        /**
         * 发布文章，构建文章对象
         * 作者id 当前的登录用户
         * 标签 将标签加入关联列表当中
         */
        Article article=new Article();
        article.setAuthorId(user.getId());
        article.setWeight(0);
          article.setViewCounts(0);
          article.setTitle(articleParam.getTitle());
          article.setSummary(articleParam.getSummary());
          article.setCommentCounts(0);
          article.setCreateDate(System.currentTimeMillis());
          article.setCategoryId(articleParam.getCategoryVo().getId());

        //插入之后 获得id
        this.articleMapper.insert(article);
        List<TagVo> tagVos = articleParam.getTagVos();
        if(tagVos!=null){
            for (TagVo tagVo : tagVos) {
                Long id = article.getId();
                ArticleTag articleTag=new ArticleTag();
                articleTag.setTagId(tagVo.getId());
                articleTag.setArticleId(id);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody=new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getArticleBodyParam().getContent());
        articleBody.setContentHtml(articleParam.getArticleBodyParam().getContentHtml());
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String,String> map=new HashMap<>();
        map.put("id",article.getId().toString());
        return RespBean.success("success",map);
    }

    private List<ArticleVo> copyList(List<Article> records,Boolean isTag,Boolean isAuthor) {
        List<ArticleVo> articleVoList=new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor));
        }
        return articleVoList;
    }

    private ArticleVo copy(Article article,Boolean isTag,Boolean isAuthor){
        ArticleVo articleVo=new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        if(isTag){
            Long articleId = article.getId();
            List<TagVo> tagsByArticleId = tagService.findTagsByArticleId(articleId);
            for (TagVo tagVo : tagsByArticleId) {
                System.out.println("=========================");
                System.out.println(tagVo);
            }
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if(isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(userService.findUserById(authorId).getNickname());
        }
       return  articleVo;
    }
}
